package com.iss.card.view.collent;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.widget.FrameLayout;

import com.iss.card.R;
import com.iss.card.common.ApplicationManager;
import com.iss.card.common.CommonValue;
import com.iss.card.common.FunctionUtil;
import com.iss.card.common.IBackKeyListener;
import com.iss.card.common.MarkProductManager;
import com.iss.card.model.MarkedProductDetailInfo;
import com.iss.card.view.ContainerActivity;
import com.iss.card.view.model.ResponseBean;
import com.iss.card.view.overrideview.IOnItemSelectedListener;
import com.iss.card.view.overrideview.ScrollViewRefresh;
import com.iss.card.view.overrideview.ScrollViewRefresh.OnRefreshListener;
import com.iss.card.webservice.WebServiceAsyncService;
import com.iss.card.webservice.WebServiceAsyncService.Operation;
import com.iss.card.webservice.WebServiceAsyncService.PostExecute;
import com.iss.card.webservice.WebServiceAsyncServiceHelper;
import com.iss.card.webservice.WebServiceManager.WebServiceRegistrationParameter;
import com.iss.card.webservice.WebServiceManager.WebServiceUrlPortManager;
import com.iss.card.webservice.WebServiceUtils;

public class CollentView implements IBackKeyListener {
	private static final String TAG = CollentView.class.getSimpleName();
	private final static int SRC_FROM_SERVER = 0x10;
	private final static int SRC_FROM_LOCAL = 0x11;
	private List<MarkedProductDetailInfo> mMarkedProductList = new ArrayList<MarkedProductDetailInfo>();

	private List<MarkedProductDetailInfo> mDisplayedList = new ArrayList<MarkedProductDetailInfo>();

	private Activity mContext;

	/** the view shows pics */
	private MarkedProductListViewContainer mContainer;
	private MarkedProductListAdapter mAdapter;
	/** refresh view init */

	private ScrollViewRefresh mScrollView;
	private View mEmptyPromptView;

	/** which page is to be displayed. */
	private int mCurrentPage = 1;

	/**
	 * it is used to listener item selected event. it will be invoked while one
	 * store in list is clicked.
	 */
	private IOnItemSelectedListener mOnItemSelectedListener = new IOnItemSelectedListener() {

		@Override
		public void OnItemSelected(ViewGroup parent, View view, int position,
				Object item) {
			Intent intent = new Intent(mContext, ContainerActivity.class);
			Log.d("MarkedProductListView", "storeId="
					+ ((MarkedProductDetailInfo) item).getStoreID() + ", pid="
					+ ((MarkedProductDetailInfo) item).getProductID());
			intent.putExtra(ApplicationManager.KEY_PUT_EXTRA_SELECTED_STORE_ID,
					((MarkedProductDetailInfo) item).getStoreID());
			// jump to store detail page and let the first product as default
			// one.
			intent.putExtra(
					ApplicationManager.KEY_PUT_EXTRA_DEFAULT_PRODUCT_ID,
					((MarkedProductDetailInfo) item).getProductID());
			intent.putExtra(ApplicationManager.INTENT_KEY,
					ApplicationManager.INTENT_FRAGMENT_STORE_DETAIL);
			((Activity) mContext).startActivityForResult(intent, 0);
		}
	};

	public CollentView(Activity context, FrameLayout view) {
		this.mContext = context;
		initFragment(context, view);
	}

	private void initFragment(Context context, FrameLayout view) {
		mEmptyPromptView = view
				.findViewById(R.id.iv_marked_product_list_view_empty_prompt);
		mScrollView = (ScrollViewRefresh) view
				.findViewById(R.id.sv_collect_scrollview);
		mScrollView.getViewTreeObserver().addOnPreDrawListener(
				new OnPreDrawListener() {

					@Override
					public boolean onPreDraw() {
						mContainer.setHeight(mScrollView.getMeasuredHeight());
						mScrollView.getViewTreeObserver()
								.removeOnPreDrawListener(this);
						return true;
					}
				});

		mAdapter = new MarkedProductListAdapter(context);
		mAdapter.setColumnCount(CommonValue.COLUMN_NUM_IN_COLLECT);
		mContainer = new MarkedProductListViewContainer(context);
		mContainer.setOnItemSelectedListener(mOnItemSelectedListener);
		mContainer.setAdapter(mAdapter);
		mScrollView.addChild(mContainer, 1);
		mScrollView.setOnScrollChangedListener(mContainer);
//		mScrollView.setFooterListener(footerlistener);

		mScrollView.setonRefreshListener(new OnRefreshListener() {

			public void onRefresh() {
				Log.d(TAG, "onRefresh");
				if (mScrollView.state == ScrollViewRefresh.REFRESHING) {
					mCurrentPage = 1;
					// get info from server again.
					loadMarkedProductList();
				}
			}
		});
	}

	/**
	 * click listener for footer view.
	 */
	OnClickListener footerlistener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// show another pic show.
			mCurrentPage++;
			mAdapter.setContents(fetchDisplayedList());
			if (mAdapter.getCount() == mMarkedProductList.size()) {
				mScrollView.setFooterViewText(R.string.loading_end);
			}
		}
	};

	public void loadMarkedProductList() {
		Log.d(TAG, "loadMarkedProductList");
		if (FunctionUtil.isUserLogIn()) {
			requestMarkedProductList();
		} else {
			responseGetMarkedProductList(SRC_FROM_LOCAL, 0, MarkProductManager
					.instance().getMarkedProductList(), 0);
		}
	}

	private SparseArray<List<MarkedProductDetailInfo>> fetchDisplayedList() {
		Log.d(TAG, "fetchDisplayedList:");
		SparseArray<List<MarkedProductDetailInfo>> list = new SparseArray<List<MarkedProductDetailInfo>>();
//		final int curNum = mCurrentPage * CommonValue.COUNT_SHOW;
//		final int totalNum = mMarkedProductList.size();
//		int maxNum = totalNum > curNum ? curNum : totalNum;
//		mDisplayedList.clear();
//		mDisplayedList.addAll(mMarkedProductList.subList(0, maxNum));
		mDisplayedList.clear();
		mDisplayedList.addAll(mMarkedProductList);		
		final int size = mDisplayedList.size();
		for (int i = 0; i < CommonValue.COLUMN_NUM_IN_COLLECT; ++i) {
			List<MarkedProductDetailInfo> tmp = new ArrayList<MarkedProductDetailInfo>();
			for (int j = i; j < size; j += CommonValue.COLUMN_NUM_IN_COLLECT) {
				Log.d(TAG, "fetchDisplayedList: column=" + i + ", row=" + j);
				tmp.add(mDisplayedList.get(j));
			}
			list.put(i, tmp);
		}

		return list;
	}

	/**
	 * get info from server.
	 */
	private void requestMarkedProductList() {
		Log.d(TAG, "requestMarkedProductList");
		WebServiceAsyncService service = new WebServiceAsyncService();
		service.setParameterToAsyncService(mContext, service.getNextToken(),
				Operation.OP_SERVICE_ARG_GET_COLLECTION,
				WebServiceRegistrationParameter.COLLECTION_GETINFO_PARAMETER,
				new String[] { FunctionUtil.getCurrentLoginUserMobile() },
				WebServiceUrlPortManager.ACTION_URL_PORT_COLLECTIONED_INFO,
				this, WebServiceAsyncServiceHelper.TYPE_HTTP_GET_INSTREAM);
		service.setPostExecute(new PostExecute() {
			@Override
			public void onAsyncServiceComplete(int token, Object result,
					int index) {
				responseGetMarkedProductList(SRC_FROM_SERVER, token, result,
						index);
			}
		});
	}

	private void responseGetMarkedProductList(int source, int token,
			Object result, int index) {

		List<MarkedProductDetailInfo> list = null;
		switch (source) {
		case SRC_FROM_SERVER:
			ResponseBean response = WebServiceUtils.getObjectResultToBaseInfo(
					result, MarkedProductDetailInfo.class);
			list = (List<MarkedProductDetailInfo>) response.getReturnList();
			break;
		case SRC_FROM_LOCAL:
			list = (ArrayList<MarkedProductDetailInfo>) result;
			break;
		default:
			return;
		}

		if (list.size() == 0) { // no marked product, show prompt view.
			mEmptyPromptView.setVisibility(View.VISIBLE);
			return;
		} else {
			mEmptyPromptView.setVisibility(View.GONE);
		}

		mMarkedProductList = list;
		mScrollView.onRefreshComplete();
		mAdapter.setContents(fetchDisplayedList());
		mScrollView.setFooterVisible(true);
		mScrollView.setFooterViewText(R.string.loading_end);
//		if (mMarkedProductList.size() > CommonValue.COUNT_SHOW) {
//			mScrollView.setFooterViewText(R.string.loading_more);
//		} else {
//			mScrollView.setFooterViewText(R.string.loading_end);
//		}
	}

	@Override
	public void cancelUpdate(Object... params) {
		if (mAdapter == null || mAdapter.getCount() == 0) {
			// Tools.onPostCheck((Integer) params[0],null, mContext, tv,-1);
		} else {
			mScrollView.onRefreshComplete();
		}
	}

	public void onDestroy() {
	}

}
